//
//  HomeViewController.m
//  Lightthings
//
//  Created by Hero on 2024/11/15.
//

#import "HomeViewController.h"
#import "HomeTodyStepModel.h"
#import "HomeItemModel.h"
#import "HomeDeviceView.h"
#import "LocationManager.h"
#import "aes.h"
@interface HomeViewController ()<FRQBluetoothManagerDelegate>
/* <#note#> */
@property (nonatomic, strong) HomeDeviceView * devicesView;
@property (nonatomic, strong) UIImageView * avatar;
@property (nonatomic, strong) UILabel * nameLab, *locationLab, *weatherLab;
@property (nonatomic, strong) CBPeripheral * per;
@property (nonatomic, strong) HomeTodyStepModel * stepM;
@property (nonatomic, strong) HomeItemModel * xinlv, *yundong, *tiwen, *shuimian, *xueyang, *xueya, *huxilv, *xindiantu, * xuetang;
@property (nonatomic, strong) NSArray * secretArr;

@end

@implementation HomeViewController
- (BOOL)can_pulldown {return NO;}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.devicesView refreshUI];
    [self readBleData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[FRQBluetoothManager shareManager] addBleDelegate:self];

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[FRQBluetoothManager shareManager] removeBleDelegate:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    
    [LocationManager.sharedInstance updateLocation:^(NSString * _Nonnull text, NSString * _Nonnull text2) {
        self.locationLab.text = text;
        self.weatherLab.text = [NSString stringWithFormat:@"%@℃",text2];
    }];
    
    [[FRQBluetoothManager shareManager] addBleDelegate:self];

}

- (void)startScanBle {
    NSArray * arr = [[FRQBluetoothManager shareManager] scanPhoneConnectPeripherals];
 
    DDLogDebug(@"获取已连接的设备 数量 %d",(int)[arr count]);

    NSArray * uuidArr = [[NSUserDefaults standardUserDefaults] valueForKey:@"lastconnectuuid"];
    
    for (CBPeripheral* peripheral in arr)
    {
        if ([uuidArr containsObject:peripheral.identifier.UUIDString]) {
            self.peripheral = peripheral;
            peripheral.deviceType = @4;
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
                if (!progressHUD) {
                    progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                }
                progressHUD.label.text = SWString(@"正在连接...");
                progressHUD.mode = MBProgressHUDModeText;
                [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:self.peripheral];
            });
        }
    }
}

- (void)initUI {
    
    _avatar = [JYInitializer jy_initImageViewWithImage:U_imageNamed(@"avatar01") on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(15);kMakeWHV(40, 40);kMakeTV(klSafeAreaEdgeInsets.top);
    }];
    _nameLab = [JYInitializer jy_initLabelWithText:@"name" textColor:KLColor(@"000000") font:U_sfont(16) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeL(self.avatar.mas_right).offset(10);
        kMakeT(self.avatar.mas_top);
    }];
    
    _locationLab = [JYInitializer jy_initLabelWithText:@"" textColor:KLColor(@"000000") font:U_font(14) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeRV(-10);
        kMakeHV(22);
        kMakeTV(klSafeAreaEdgeInsets.top);
    }];
    
    _weatherLab = [JYInitializer jy_initLabelWithText:@"" textColor:KLColor(@"000000") font:U_font(14) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeRV(-10);
        kMakeHV(22);
        kMakeT(self.locationLab.mas_bottom);
    }];
    
    _devicesView = [[HomeDeviceView alloc] initWithFrame:CGRectMake(15, klSafeAreaEdgeInsets.top +  50, kScreenWidth - 30, 120)];
    [self.view addSubview:_devicesView];
    
    self.collectionInsets = kEdge(klSafeAreaEdgeInsets.top +  44 + 135, 0, 0, 0);
    
    MainSectionModel * s = [[MainSectionModel alloc] init];
    [s sectionInsets:kEdge(10, 15, 15, 15) ls:10 is:10];
    
    
    HomeTodyStepModel * stepM = [[HomeTodyStepModel alloc] init];
    [s.items addObject:stepM];
    _stepM = stepM;
    
    MainSectionModel * s2 = [[MainSectionModel alloc] init];
    [s2 sectionInsets:kEdge(10, 15, 15, 15) ls:10 is:10];
    s2.layoutAlignLeft = YES;
    
    _xinlv = [HomeItemModel cModelWithImage:@"icon_home_heart" Title:SWString(@"心率") Value:[self defaultValueString:@"0" Unit:@"bmp"] ViewColor:@"#FFEEF1"];
    _xinlv.action = kMsgPackForward(@"clickItem:", WKProxy(self),@(RecordType_HeartReat));
    [s2.items addObject:_xinlv];
    
    _yundong = [HomeItemModel cModelWithImage:@"icon_home_sport" Title:SWString(@"运动记录") Value:[self defaultValueString:@"0" Unit:SWString(@"公里")] ViewColor:@"#FFF2E3"];
    _yundong.action = kMsgForward(@"showSportView", WKProxy(self));
    [s2.items addObject:_yundong];
    
    _tiwen = [HomeItemModel cModelWithImage:@"icon_home_temperature" Title:SWString(@"体温") Value:[self defaultValueString:@"0" Unit:@"℃"] ViewColor:@"#EAF8FA"];
    [s2.items addObject:_tiwen];
    
    NSMutableAttributedString * hourstring = [self defaultValueString:@"0" Unit:SWString(@"时")];
    [hourstring appendAttributedString:[self defaultValueString:@"0" Unit:SWString(@"分")]];
    
    _shuimian = [HomeItemModel cModelWithImage:@"icon_home_sleep" Title:SWString(@"睡眠记录") Value:hourstring ViewColor:@"#F8EFFF"];
    _shuimian.action = kMsgPackForward(@"clickItem:", WKProxy(self),@(RecordType_Sleep));
    [s2.items addObject:_shuimian];
    
    _xueyang = [HomeItemModel cModelWithImage:@"icon_home_blood_oxygen" Title:SWString(@"血氧") Value:[self defaultValueString:@"0" Unit:@"%"] ViewColor:@"#FFE7E4"];
    _xueyang.action = kMsgPackForward(@"clickItem:", WKProxy(self),@(RecordType_BloodOxygen));
    [s2.items addObject:_xueyang];
    
    _xueya = [HomeItemModel cModelWithImage:@"icon_home_blood_pressure" Title:SWString(@"血压") Value:[self defaultValueString:@"0" Unit:@"mmHg"] ViewColor:@"#FFE7F1"];
    _xueya.action = kMsgPackForward(@"clickItem:", WKProxy(self),@(RecordType_BloodPressure));
    [s2.items addObject:_xueya];
    
    
    _huxilv = [HomeItemModel cModelWithImage:@"icon_home_qingxu" Title:SWString(@"呼吸率") Value:[self defaultValueString:@"0" Unit:SWString(@"次/分")] ViewColor:@"#E1FFEC"];
    _huxilv.action = kMsgPackForward(@"clickItem:", WKProxy(self),@(RecordType_RespiratoryReat));
    [s2.items addObject:_huxilv];
    
    _xindiantu = [HomeItemModel cModelWithImage:@"icon_home_ecg" Title:SWString(@"心电图") Value:[self defaultValueString:@"窦性心律" Unit:@""] ViewColor:@"#FFFEDA"];
    [s2.items addObject:_xindiantu];
   
    _xuetang = [HomeItemModel cModelWithImage:@"icon_home_blood_glucose" Title:SWString(@"血糖") Value:[self defaultValueString:@"0" Unit:@"mmol/L"] ViewColor:@"#FFEDE9"];
    
    [s2.items addObject:_xuetang];
      
    HomeItemModel *  yundong = [HomeItemModel cModelWithImage:@"icon_home_blood_glucose" Title:SWString(@"运动轨迹") Value:nil ViewColor:@"#FFEDE9"];
    yundong.action = kMsgForward(@"showMapView", WKProxy(self));
    [s2.items addObject:yundong];
    
    self.dataSources = @[s, s2];
    
    // Do any additional setup after loading the view.
}

- (NSMutableAttributedString *)defaultValueString:(NSString *)value Unit:(NSString *)unit {
    return [SWTool attS1:value s2:[NSString stringWithFormat:@"  %@",unit] f1:U_bfont(22) c1:KLColor(@"000000") f2:U_font(14) c2:KLColor(@"000000")];
}

- (void)readBleData {
    NSArray< CBPeripheral *> * arr = [FRQBluetoothManager shareManager].curPeripherals;
    if (arr.count) {
        self.per = arr.firstObject;
        if (self.per.deviceType.intValue == BleDevice_Watch) {
            [self readTargetData];
            [LocationManager.sharedInstance startUpdateLocationToPeripheral:self.per];
        }else if (self.per.deviceType.intValue == BleDevice_Pillow) {
//            [PillowCommandTool.sharedInstance writeStormCommand:Pillow_StartMassage ToPeripheral:self.per Value:@[@(0x01), @(0x0A)] reBack:^(NSString * _Nonnull result) {
//                            
//            }];
        }
    }
}

/// 目标步数
- (void)readTargetData {
    [WatchCommandTool.sharedInstance  readStepTargetData:^(BOOL success, unsigned long stepData) {
        if (success) {
            self.stepM.targetNum  = stepData;
            self.per.targetStep = [NSString stringWithFormat:@"%ld", stepData];
            [self reloadIfNeeded];
        }
        [self readRealTimeData];
    } ToPeripheral:self.per];
}

/// 心率 步数 距离 热量
- (void)readRealTimeData {
    [WatchCommandTool.sharedInstance readRealTimeDataFromPeripheral:self.per Block:^(BOOL success, unsigned long stepData, unsigned long caloriesData, unsigned long distanceData, unsigned long heartRateData, unsigned long electricData) {
        if (success) {
            self.stepM.currentNum = stepData;
            self.stepM.calories = caloriesData;
            self.stepM.distance = distanceData;
            self.stepM.heartRate = heartRateData;
            
            self.xinlv.value = [self defaultValueString:[NSString stringWithFormat:@"%ld", heartRateData] Unit:SWString(@"次/分")];
            self.huxilv.value = [self defaultValueString:[NSString stringWithFormat:@"%ld", heartRateData / 4] Unit:SWString(@"次/分")];
            
            self.yundong.value = [self defaultValueString:[NSString stringWithFormat:@"%ld", distanceData] Unit:SWString(@"公里")];
            
            [self reloadIfNeeded];
        }
        [self readBloodOxygenData];
    }];
}

/// 血氧
- (void)readBloodOxygenData {
    [WatchCommandTool.sharedInstance readBloodOxygenData:^(BOOL success, NSArray * _Nonnull allData) {
        if (success) {
            NSString * itemStr = allData.firstObject;
            NSString * rateD = [itemStr substringFromIndex:8];
            NSInteger  bloodOxygen = strtoll([[NSString stringWithFormat:@"0x%@",rateD] UTF8String], 0, 16);
            self.xueyang.value = [self defaultValueString:[NSString stringWithFormat:@"%ld",bloodOxygen] Unit:@"%"];
            [self reloadIfNeeded];
        }
    } ToPeripheral:self.per];
}


- (void)clickItem:(NSNumber *)type {
    if (!self.per) {
        ZHRunEngine(kRunCMD(@"_show_searchView"), nil);
        return;
    }
    if (self.per.deviceType.intValue == BleDevice_Watch) {
        if (type.intValue == RecordType_HeartReat || type.intValue == RecordType_RespiratoryReat || type.intValue == RecordType_Sleep || type.intValue == RecordType_BloodOxygen || type.intValue == RecordType_BloodPressure) {
            ZHRunEngine(kRunCMDINFO(@"_show_HomeDataListView", @{@"type":type, @"uuid":self.per.identifier.UUIDString}), nil);
        }
    }
   
}
- (void)showMapView {
    if (self.per.deviceType.intValue == BleDevice_Watch) {
        ZHRunEngine(kRunCMDINFO(@"show_MapView", @{ @"uuid":self.per.identifier.UUIDString}), nil);
    }
}

- (void)showSportView {
    self.tabBarController.selectedIndex = 1;
}

-(void)onBLEManagerStateChange:(id<FRBleAbility>)ability{
    
    switch (ability.state) {
        case FRQManagerStateUnsupported:
        {
//            toastHud.label.text = @"请检查你蓝牙使用权限或检查设备问题";
        }
            break;
        case FRQManagerStateUnauthorized:
        {
//            toastHud.label.text = @"蓝牙设备暂无法使用，请在设置中授权";
        }
            break;
        case FRQManagerStatePoweredOff:
        {
//            toastHud.label.text =@"蓝牙已关闭";
            
            [[FRQBluetoothManager shareManager] cancelScan];
        }
            break;
        case FRQManagerStatePoweredOn:
        {
//            toastHud.label.text = @"蓝牙已打开";
            //scan
            [self  startScanBle];
        }
            break;
        default:
            break;
    }
    
}

// MARK:   🔥🔥🔥🔥🔥🔥🔥 蓝牙Manager  代理方法 🔥🔥🔥🔥🔥🔥🔥
- (void)onBLEManagerDisconnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.devicesView refreshUI];
}

-(void)onBLEManagerConnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    DDLogDebug(@"首页连接成功");
    [self.devicesView refreshUI];
}


- (void)onBLEManagerReady:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    // 先握手，再发绑定-》读取功能列表-》设备信息-》其他数据交互
    if (peripheral.deviceType.intValue == BleDevice_Pillow) {
        [PillowCommandTool.sharedInstance updateDateAndTimeCallBack:^(NSString * data) {
                    
        } RealTimeData:NO StopSwith:NO ToPeripheral:peripheral];
        
    }else if (peripheral.deviceType.intValue == BleDevice_Watch) {
        [self handshakeWithPer:peripheral];
    }else  {
        peripheral.deviceType = @(BleDevice_Watch);
        [self handshakeWithPer:peripheral];
    }
    [self.devicesView refreshUI];
}

- (void)handshakeWithPer:(CBPeripheral *)peripheral {

    unsigned char mac[16] ;
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 16; i ++) {
        int a = arc4random() % 256;
        char charValue = (char)a;
        mac[i] = charValue;
    }
    DDLogDebug(@"Home加密前 %@", [NSData dataWithBytes:mac length:sizeof(mac)]);
    self.secretArr = [self convertDataToArray:[NSData dataWithBytes:mac length:sizeof(mac)]];
    Cipher(mac);
    DDLogDebug(@"Home加密后 %@", [NSData dataWithBytes:mac length:sizeof(mac)]);

    for (int i = 0; i < 16; i++) {
        NSNumber * num = [NSNumber numberWithUnsignedChar:mac[i]];
        [arr addObject:num];
    }
    DDLogDebug(@"Home第一步：开始握手");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance  writeStormCommand:Command_Handshake ToPeripheral:peripheral Value:arr reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (backData.length) {
            NSString * value = [backData substringWithRange:NSMakeRange(26, 32)];
            toast(value);
            if ([value isEqualToString:[self.secretArr componentsJoinedByString:@""]]) {
                toast(@"握手成功");
                [self bindWithPer:peripheral];
            }else{
                
                [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:peripheral];
                toast(@"握手失败，断开链接");
            }
        }
        
    }];
}

- (void)bindWithPer:(CBPeripheral *)peripheral {
    DDLogDebug(@"Home第二步：开始绑定");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance  writeStormCommand:Command_Bind ToPeripheral:peripheral Value:@[@(1 & 0xff),@(1 & 0xff),@(1 & 0xff),@(1 & 0xff)] reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (backData.length) {
            [self getChipInfo:peripheral];
        }else {
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:peripheral];
            toast(@"Home绑定失败，断开链接");
        }
    }];
}

- (void)getChipInfo:(CBPeripheral *)peripheral {
    DDLogDebug(@"Home第三步：读取芯片信息");
    [WatchCommandTool.sharedInstance writeStormCommand:Command_ChipInfo ToPeripheral:peripheral Value:@[] reBack:^(NSString * _Nonnull backData) {
        if (backData.length) {
            ///  54590101800174000d00020009000001465238303038
            peripheral.chipInfo = [backData substringFromIndex:26];
            [self getFounctionsWithPer:peripheral];
        }else {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:peripheral];
            toast(@"Home绑定失败，断开链接");
        }
    }];
}


- (void)getFounctionsWithPer:(CBPeripheral *)peripheral {
    DDLogDebug(@"Home第四步：获取功能列表");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance  writeStormCommand:Command_FounctionList ToPeripheral:peripheral Value:nil reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (backData.length) {
            NSString * valueStr = [backData substringFromIndex:26];
            NSMutableArray * list= [[NSMutableArray alloc] init];
            for (int i = 1; i < 6; i++) {
                NSString * s1 = [NSString stringWithFormat:@"%lld",strtoll([[NSString stringWithFormat:@"0x%@",[valueStr substringWithRange:NSMakeRange(2 * i, 2)]] UTF8String], 0, 16)];
                NSString *byte1 = [SWTool decimalToBinary:s1];
                
                for (int j = 7; j >= 0; j --) {
                    BOOL b =  [[byte1 substringWithRange:NSMakeRange(j, 1)] isEqualToString:@"1"];
                    [list addObject:@(b)];
                }
            }

            peripheral.founctionlist = list;
            
            [self getDeviceInfo:peripheral];
            
        }else {
            [self getDeviceInfo:peripheral];
        }
    }];

}


- (void)getDeviceInfo:(CBPeripheral *)peripheral {
    DDLogDebug(@"Home第五步：获取设备信息");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [WatchCommandTool.sharedInstance writeStormCommand:Command_DeviceInfo ToPeripheral:peripheral Value:nil reBack:^(NSString * _Nonnull backData) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        if (backData.length) {
            DDLogDebug(@"Home第六步：更新时间");
            [WatchCommandTool.sharedInstance updateDateAndTimeCallBack:^(BOOL success) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                toast(@"链接成功");
                [self back];
            } ToPeripheral:peripheral];
//        }
    }];
}

- (NSArray *)convertDataToArray:(NSData *)data {
    if (!data || [data length] == 0) {
        return nil;
    }
    NSMutableArray *stringArray = [[NSMutableArray alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [stringArray addObject:hexStr];
            } else {
                [stringArray addObject:[NSString stringWithFormat:@"0%@", hexStr]];
            }
        }
    }];
    
    return stringArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
